package com.ajx.blog.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import com.ajx.blog.entity.Admin;
import com.ajx.blog.entity.Article;
import com.ajx.blog.entity.ArticleCheckMessage;
import com.ajx.blog.entity.ArticleDistribute;
import com.ajx.blog.mapper.AdminMapper;
import com.ajx.blog.mapper.ArticleCheckMessageMapper;
import com.ajx.blog.mapper.ArticleDistributeMapper;
import com.ajx.blog.mapper.ArticleMapper;
import com.ajx.blog.service.api.ArticleDistributeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ArticleDistributeServiceImpl extends ServiceImpl<ArticleDistributeMapper, ArticleDistribute>
        implements ArticleDistributeService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleCheckMessageMapper articleCheckMessageMapper;

    @Autowired
    private ArticleDistributeMapper articleDistributeMapper;

    /**
     * @param {Integer} articleId 文章ID
     * @return {boolean} 是否分配成功
     * 
     * @description: 给文章审核员分配文章
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean assigningTask(Integer articleId) {
        // 查看是否有此文章 如果其状态是 待审核(0) 或者 审核不通过(-1) 才可以分配审核员 否则不能分配
        Article article = articleMapper.selectById(articleId);
        if (article == null || "1".equals(article.getAstatus())) {
            return false;
        }
        // 查看是否分配了审核员且状态是 未审核(-1) 如果有则不分配
        QueryWrapper<ArticleDistribute> qw = new QueryWrapper<>();
        qw.eq("article_id", articleId);
        qw.eq("astatus", "-1");
        ArticleDistribute articleDistribute = articleDistributeMapper.selectOne(qw);
        if (articleDistribute != null) {
            return false;
        }
        // 找所有普通文章审核员,存储到集合,随机挑一位分配任务
        List<Admin> adminList = adminMapper.selectSpecificPermissionAdmin("ROLE_CHECK_EMP");
        if (adminList.size() > 0) {
            int randomId = 0;
            if (articleId > 100) {
                String str = String.valueOf(articleId);
                randomId = Integer.parseInt(str.substring(str.length() - 3)) % adminList.size();
            } else {
                randomId = articleId % adminList.size();
            }
            // ThreadLocalRandom t = ThreadLocalRandom.current();
            // int randomId = t.nextInt(0, adminList.size() - 1);
            // System.out.println("==================================");
            // System.out.println(randomId);
            // System.out.println(adminList.size());
            // System.out.println("==================================");

            int adminId = adminList.get(randomId).getAdminId();
            ArticleDistribute art = new ArticleDistribute();
            art.setArticleId(articleId); // 文章ID
            art.setAdminId(adminId); // 管理员ID
            art.setAstatus("-1"); // 表示未审核
            art.setRemark("审核完成删除此记录,未审核-1"); // 备注
            if (articleDistributeMapper.insert(art) > 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param {Integer} adminId 管理员ID
     * @param {Integer} articleId 文章ID
     * @param {String}  astatus 审核状态 -1审核不通过 1 审核通过
     * @param {String}  msg 管理员提交的审核信息 如果没有则按数据库设置的默认值添加
     * @return {boolean} 审核操作是否完成 true/false
     * 
     * @description: 管理员审核文章
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean checkArticle(Integer adminId, Integer articleId, String astatus, String msg) {
        // 1、审核完成,将任务分配纪录在ArticleDistribute表中删除
        UpdateWrapper<ArticleDistribute> articleDistributeUW = new UpdateWrapper<>();
        articleDistributeUW.eq("article_id", articleId);
        articleDistributeUW.eq("admin_id", adminId);
        articleDistributeUW.eq("astatus", "-1");
        Integer result1 = articleDistributeMapper.delete(articleDistributeUW);
        // 2、ArticleCheckMessage存储审核信息
        ArticleCheckMessage articleCheckMessage = new ArticleCheckMessage();
        articleCheckMessage.setTitle(msg);
        articleCheckMessage.setAdminId(adminId);
        articleCheckMessage.setArticleId(articleId);
        Integer result2 = articleCheckMessageMapper.insert(articleCheckMessage);
        // 3、Article表更新状态 -1审核不通过 0待审核 1审核通过
        UpdateWrapper<Article> articleUW = new UpdateWrapper<>();
        articleUW.eq("aid", articleId);
        Article updateArticleArgs = new Article();
        updateArticleArgs.setAstatus(astatus);
        updateArticleArgs.setRemark("-1审核不通过 1 审核通过 0待审核");
        Integer result3 = articleMapper.update(updateArticleArgs, articleUW);
        return result1 > 0 && result2 > 0 && result3 > 0;
    }

    /**
     * @param {Integer} adminId 管理员ID
     * @param {Integer} articleId 文章ID
     * @return {boolean} 上报操作是否完成 true/false
     * 
     * @description: 普通文章审核员将文章交给审核经理审核
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean reportArticle(Integer adminId, Integer articleId) {
        // 找所有文章审核经理,存储到集合,将自己处理不了的文章随机上报给文章审核经理
        List<Admin> adminList = adminMapper.selectSpecificPermissionAdmin("ROLE_CHECK_MANAGE");
        int index = 0;
        if (articleId > 100) {
            String str = String.valueOf(articleId);
            index = Integer.parseInt(str.substring(str.length() - 3)) % adminList.size();
        }
        int managerId = adminList.get(index).getAdminId();
        UpdateWrapper<ArticleDistribute> articleDistributeUW = new UpdateWrapper<>();
        ArticleDistribute articleDistribute = new ArticleDistribute();
        articleDistribute.setAdminId(managerId);
        articleDistribute.setRemark("审核员:" + adminId + "上报");
        articleDistributeUW.eq("article_id", articleId);
        articleDistributeUW.eq("admin_id", adminId);
        articleDistributeUW.eq("astatus", "-1");
        return articleDistributeMapper.update(articleDistribute, articleDistributeUW) > 0;
    }

    /**
     * @param {Integer} adminId 管理员ID
     * @param {Integer} page 当前页码数
     * @return { PageInfo<Article>} 封装的分页数据,未审核的文章列表(只有aid,title,createtime字段)
     * 
     * @description: 管理员查询未审核的文章列表,用于列表展示页面,不用查询全部信息,详细信息在详情页面查询
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public PageInfo<Article> selectunCheckedArticle(Integer adminId, Integer page) {
        // 1、在Article_Distribute表中查询分配给自己的文章且未审核的文章
        QueryWrapper<ArticleDistribute> articleDistributeQW = new QueryWrapper<>();
        // 查询条件,只查询文章id字段
        articleDistributeQW.select("article_id").eq("admin_id", adminId).eq("astatus", "-1");
        // 自己的任务集合
        List<ArticleDistribute> articleDistributeList = articleDistributeMapper.selectList(articleDistributeQW);
        // 将文章id存在一个list中
        List<Integer> aidList = new ArrayList<>();
        // 如果集合为空则直接返回null
        if (articleDistributeList.isEmpty()) {
            return new PageInfo<>(new ArrayList<>());
        }
        // 遍历任务集合,将文章id存在list中
        for (int i = 0; i < articleDistributeList.size(); i++) {
            aidList.add(articleDistributeList.get(i).getArticleId());
        }
        // 2、通过文章id在文章数据表中查询待审核的文章
        QueryWrapper<Article> articleQW = new QueryWrapper<>();
        // 查询条件
        articleQW.select("aid", "title", "createtime").in("aid", aidList);
        // 3、返回数据
        PageHelper.startPage(page, 5);
        List<Article> articleList = articleMapper.selectList(articleQW);
        return new PageInfo<>(articleList);
    }

    /**
     * @param {Integer} adminId 管理员ID
     * @param {Integer} page 当前页码数
     * @return { PageInfo<ArticleCheckMessage>}
     *         封装的分页数据,审核过的文章审核信息列表
     *         articleId文章ID,remark文章标题,title审核评价,createtime审核时间
     * 
     * @description: 管理员查询审核过的文章审核信息列表,用于列表展示页面
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public PageInfo<ArticleCheckMessage> selectCheckedArticle(Integer adminId, Integer page) {
        PageHelper.startPage(page, 5);
        List<ArticleCheckMessage> msgList = articleCheckMessageMapper.selectMsgList(adminId);
        return new PageInfo<>(msgList);
    }

    /**
     * @param {Integer} articleId 文章id
     * @return {Article} 被查出来的文章对象
     * 
     * @description: 根据文章id查找文章
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Article selectArticleById(Integer articleId) {
        if (articleId != null && articleId > 0) {
            return articleMapper.selectById(articleId);
        }
        return null;
    }

}
